package com.LeetCode.why73;

/**
 * Created by Aqc on 2017/6/28.
 */
public class SetMatrixZeroes {
    public void setZeroes(int[][] matrix) {
        //如果某一元素为零，则将该行第一个元素和该列第一个元素置零，作为标记；最后全置零。
        // 但是存在问题：首行全置零后，会导致列全置零！！
        //解决方法，标注第一行和第一列是否需要置零，最后再改动。
        if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) {
            return;
        }
        int m = matrix.length;
        int n = matrix[0].length;

        boolean row0 = false;
        boolean cul0 = false;
        for (int i = 0; i < m; i++) {
            if (matrix[i][0] == 0) {
                cul0 = true;
                break;
            }
        }
        for (int j = 0; j < n; j++) {
            if (matrix[0][j] == 0) {
                row0 = true;
                break;
            }
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (matrix[i][j] == 0) {
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                }
            }
        }

        for (int i = 1; i < m; i++) {
            if (matrix[i][0] == 0) {
                for (int j = 1; j < n; j++) {
                    matrix[i][j] = 0;
                }
            }

        }
        for (int j = 1; j < n; j++) {
            if (matrix[0][j] == 0) {
                for (int i = 1; i < m; i++) {
                    matrix[i][j] = 0;
                }
            }
        }
        if (cul0 == true) {
            for (int i = 0; i < m; i++) {
                matrix[i][0] = 0;
            }
        }
        if (row0 == true) {
            for (int j = 0; j < n; j++) {
                matrix[0][j] = 0;
            }
        }
        return;
    }

    public static void main(String[] args) {//成功！
        int[][] m = {{0, 0, 0, 5}, {4, 3, 1, 4}, {0, 1, 1, 4}, {1, 2, 1, 3}, {0, 0, 1, 1}};
        new SetMatrixZeroes().setZeroes(m);
        //setZeroes(m);//static修饰的setZeros()时才能直接用

        for (int i = 0; i < m.length; i++) {
            for (int j = 0; j < m[0].length; j++) {
                System.out.print(" " + m[i][j]);
            }
            System.out.println();
        }
    }
}
